<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns="http://www.w3.org/1999/xhtml">

<head lang="en">
    <meta charset="UTF-8">
    <title>角色管理</title>
    <link rel="stylesheet" href="../../../assert/css/font.css" th:href="@{/assert/css/font.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap.min.css" th:href="@{/assert/css/bootstrap.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap-table.css" th:href="@{/assert/css/bootstrap-table.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrap-select.min.css" th:href="@{/assert/css/bootstrap-select.min.css}"/>
    <link rel="stylesheet" href="../../../assert/css/bootstrapValidator.css"  th:href="@{/assert/css/bootstrapValidator.css}"/>
    <link rel="stylesheet" href="../../../assert/css/toastr.min.css" th:href="@{/assert/css/toastr.min.css}"/>
    <link href="../../../assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/styles/jqx.base.css" rel="stylesheet"
          th:href="@{/assert/js/lib/jqwidgets-ver4.0.0/jqwidgets/styles/jqx.base.css}"/>
    <link rel="stylesheet" href="../../../assert/css/style.css" th:href="@{/assert/css/style.css}"/>
    <link rel="stylesheet" href="../../../assert/css/index.css" th:href="@{/assert/css/index.css(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"/>
    <link rel="stylesheet" href="../../../assert/css/common.css" th:href="@{/assert/css/common.css}"/>
    <link href="../../../assert/css/plugin/jsTree/style.min.css" th:href="@{/assert/css/plugin/jsTree/style.min.css}"/>
    <link href="../../../assert/css/plugin/jsTree/themes/default/style.css" rel="stylesheet"
          th:href="@{/assert/css/plugin/jsTree/themes/default/style.css}">
</head>
<body class="laydate_body">
<div class="wrapper wrapper-content">
    <div class="ibox">
        <!--<div class="con-title">-->
            <!--<h4>角色管理</h4>-->
        <!--</div>-->
        <div class="resourceCon">
            <div class="con-operation clearfix">
                <div class="cquery  clearfix">
                    <div class="search_group">
                        <label class="control-label">状态类型：</label>
                        <div class="control-inline">
                            <select id="statusSearch" class="selectpicker" data-live-search="true"
                                    data-live-search-style="begins" title="请选择状态" multiple>
                                <option value="1">启用</option>
                                <option value="0">停用</option>
                            </select>
                        </div>
                    </div>
                    <div class="search_group">
                        <div class="querySearch">
                            <input id="codeSearch" class="form-control" type="text" placeholder="请输入角色标识"/>
                            <input id="nameSearch" class="form-control" type="text" placeholder="请输入角色名称"/>
                        </div>
                    </div>
                    <div class="search_group">
                        <button id="searchBtn" type="button" class=" querybtn btn ">查询</button>
                        <button id="reset" type="reset" class="btn  btn-default">重置</button>
                    </div>

                </div>
                <!--   <a class="cblue">高级查询</a> -->
                <div class="obtns clearfix">
                    <button class="btn btn-default" type="button" data-toggle="modal" data-target="#roleModal">
                        <i class="fa fa-plus"></i>添加角色
                    </button>
                    <button id="editBtn" class="btn btn-default" type="button"><i
                            class="fa fa-pencil"></i>修改
                    </button>
                    <button id="batchDeleteBtn" class="btn btn-default" type="button" data-toggle="modal"><i
                            class=" fa fa-trash"></i>删除
                    </button>
                    <button id="batchOnBtn" class="btn btn-default " type="button"><i class="fa fa-power-off"></i>启用
                    </button>
                    <button id="batchOffBtn" class="btn btn-default" type="button"><i class="fa fa-stop"></i>停用
                    </button>
                    <button id="authorBtn" class="btn btn-default" type="button"><i class="fa fa-get-pocket"></i>授权
                    </button>
                    <button id="refreshRoleBtn" class="btn btn-default" type="button"><i
                            class="fa fa-refresh"></i>刷新系统角色
                    </button>
                </div>
            </div>
            <table id="roleTable"></table>
            <!-- 角色管理Modal -->
            <div class="modal fade" id="roleModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">添加角色</h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal" role="form" id="roleManageForm">
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">父级角色：</label>
                                    <div class="col-sm-7">
                                        <select class="roleTypepicker selectpicker" name="parentroleid"
                                                id="addParentSelect">
                                            <option value="" selected>请选择</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label"><span class="respan">*</span>角色标识：</label>
                                    <div class="col-sm-7">
                                        <input type="text" class="form-control" name="code" placeholder="请输入角色标识">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label"><span class="respan">*</span>角色名称：</label>
                                    <div class="col-sm-7">
                                        <input type="text" class="form-control" name="name" placeholder="请输入角色名称">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">备注：</label>
                                    <div class="col-sm-7">
                                        <textarea class="form-control" name="description"
                                                  placeholder="请输入内容"></textarea>
                                    </div>
                                </div>
                                <button type="reset" id="addResetBtn" hidden>重置</button>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="savebtn btn btn-primary" id="addSaveBtn">保存</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--角色修改modal -->
            <div class="modal fade" id="editRoleModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title">修改角色</h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal" role="form" id="editRoleForm">
                                <input type="hidden" id="roleId" name="id" value=""/>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">父级角色：</label>
                                    <div class="col-sm-7">
                                        <select class="roleTypepicker selectpicker" name="parentroleid"
                                                id="editParentSelect">
                                            <option value="" selected>请选择</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">角色标识：</label>
                                    <div class="col-sm-7">
                                        <input type="text" class="form-control" name="code" placeholder="请输入角色标识">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">角色名称：</label>
                                    <div class="col-sm-7">
                                        <input type="text" class="form-control" name="name" placeholder="请输入角色名称">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-4 control-label">备注：</label>
                                    <div class="col-sm-7">
                                        <textarea class="form-control" name="description"
                                                  placeholder="请输入内容"></textarea>
                                    </div>
                                </div>
                                <button type="reset" id="editResetBtn" hidden>重置</button>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="savebtn btn btn-primary" id="editSaveBtn">保存</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--提示角色被使用中 modal -->
            <div class="modal fade" id="tipsModal" tabindex="-1" role="dialog" aria-labelledby="tipsModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="tipsModalLabel">删除角色</h4>
                        </div>
                        <div class="modal-body">
                            <p>该角色下已分配用户或者已授权，如删除该角色，则与该角色相关的权限信息都将被删除，是否继续</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="csavebtn btn btn-primary">确定</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--确定 modal -->
            <div class="modal fade" id="enshureModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <input type="hidden" id="deleteId" value=""/>
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">删除角色</h4>
                        </div>
                        <div class="modal-body">
                            <p>确定删除吗</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="csavebtn btn btn-primary">确定</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--子角色一并删除确定 modal -->
            <div class="modal fade" id="delChildModal" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
                 data-backdrop=false>
                <div class="modal-dialog" role="document">
                    <input type="hidden" id="deleteIds" value=""/>
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="ModalLabel">删除角色</h4>
                        </div>
                        <div class="modal-body">
                            <p>选中角色下包含并未使用的子角色，是否一并删除？</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="csavebtn btn btn-primary">确定</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--为角色授权模态框2-->
            <div class="modal fade" id="authorModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel32"
                 data-backdrop="static" data-keyboard="false">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                            <h4 class="modal-title" id="myModalLabel32">
                                为角色【 <span id="roleName"></span> 】授权
                            </h4>
                            <input type="hidden" name="roleId" id="authRoleId">
                        </div>
                        <div class="modal-body">
                            <div class="no-permission">
                                <span>权限列表 </span>
                                <p><div id="authorTree"  clsss="ctree"></div></p>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="savebtn btn btn-primary" id="authorSaveBtn">保存</button>
                            <button type="button" class="cancelbtn btn btn-default" data-dismiss="modal">取消</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<a id="basePath" th:href="@{/}"></a>
<script src="../../../assert/js/jquery.js" th:src="@{/assert/js/jquery.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/bootstrap.min.js" th:src="@{/assert/js/bootstrap.min.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<!--<script src="../../../assert/js/bootstrap-table.js" th:src="@{/assert/js/bootstrap-table.js}"></script>-->
<script src="../../../assert/js/plugin/bootstrap-table/bootstrap-table.min.js"
        th:src="@{/assert/js/plugin/bootstrap-table/bootstrap-table.min.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/bootstrap-select.js" th:src="@{/assert/js/bootstrap-select.js}"></script>
<script src="../../../assert/js/bootstrapValidator.js" th:src="@{/assert/js/bootstrapValidator.js}"></script>
<script src="../../../assert/js/base.js" th:src="@{/assert/js/base.js(v_=${@commonController.getSysConfigByPK('CACHE_CODE')})}"></script>
<script src="../../../assert/js/toastr.min.js" th:src="@{/assert/js/toastr.min.js}"></script>
<script src="../../../assert/js/plugin/jsTree/jstree.min.js" th:src="@{/assert/js/plugin/jsTree/jstree.min.js}"></script>
<script type="text/javascript">
    //项目名称
    var basePath = $("#basePath").attr("href");
    var TableInit = function () {
        var oTableInit = new Object();
        //初始化Table
        oTableInit.Init = function () {
            $('#roleTable').bootstrapTable({
                url: basePath + "rest/role/rolesByPage", //请求后台的URL（*）
                method: "post", //请求方式（*）
                dataType: "json",
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",
                dataField: "rows", //服务端返回数据键值 就是说记录放的键值是rows，分页时使用总记录数的键值为total
                totalField: "total",
                striped: true, //是否显示行间隔色
                cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true, //是否显示分页（*）
                sortable: true, //是否启用排序
                sortName: "id", //排序方式
                sortOrder: "desc", //排序方式
                clickToSelect: true,
                queryParams: oTableInit.queryParams, //传递参数（*）
                queryParamsType: "", //  queryParamsType = 'limit' 参数: limit, offset, search, sort, order;
                sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1, //初始化加载第一页，默认第一页
                pageSize: 10, //每页的记录行数（*）
                pageList: [10, 15, 20, 25], //可供选择的每页的行数（*）
                idField: "id",
                uniqueId: "id", //每一行的唯一标识，一般为主键列
                columns: [{
                    field: 'id',
                    title: 'ID',
                    sortable: true,
                    visible: false
                },
                    {
                        field: 'checkStatus',
                        title: '全选',
                        checkbox: true
                    },
                    {
                        field: 'code',
                        title: '角色标识',
                        sortable: true
                    },
                    {
                        field: 'name',
                        title: '角色名称',
                        sortable: true
                    },
                    {
                        field: 'status',
                        title: '状态',
                        sortable: true,
                        formatter: function (value, row, index) {
                            if (value == "0") return "停用";
                            else return "启用";
                        }
                    },
                    {
                        field: 'description',
                        title: '备注',
                        sortable: true,
                        width:200,
                        formatter: function (value, row, index) {
                            if(value == null){
                                value=""
                            }
                            return "<div class='onoteBoxTable' title='"+value+"'>"+value+"</div>";
                        }
                    }
                ],
                formatLoadingMessage: function () {
                    return "请稍等，正在加载中...";
                },
                formatNoMatches: function () { //没有匹配的结果
                    return '无符合条件的记录';
                },
                onLoadSuccess: function (data) {  //加载成功时执行
                    resize.me();
                },
                onLoadError: function (data) {
                    $('#roleTable').bootstrapTable('removeAll');
                },
                responseHandler: function (res) {
                    return {
                        total: res.totalCount,
                        rows: res.result
                    };
                }
            });
        };
        //得到查询的参数
        oTableInit.queryParams = function (params) {
            var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                "pageSize": params.pageSize,
                "pageNum": params.pageNumber,
                "sortName": this.sortName,
                "sortOrder": this.sortOrder,
                "status": $("#statusSearch").val() != null ? $("#statusSearch").val().join(",") : null,
                "name": $.trim($("#nameSearch").val()),
                "code": $.trim($("#codeSearch").val())
            };
            return temp;
        };
        return oTableInit;
    };

    // 添加角色
    var roleAddFun = {
        init: function () {
            roleAddFun.formInit();
            roleAddFun.save();
        },
        formInit: function () {
            // 初始化表单
            $("#roleModal").on("show.bs.modal", function () {
                $("#addParentSelect").html("<option value=\"\" selected>请选择</option>");
                $.get(basePath + "rest/role/parentRoleAll", function (data) {
                    $.each(data, function (index, role) {
                        $("#addParentSelect").append("<option value=\"" + role.id + "\">" + role.name + "</option>");
                    });
                    $("#addParentSelect").selectpicker('refresh');
                    $("#addParentSelect").selectpicker('render');
                });
                $("#addResetBtn").click();
            });
        },
        save: function () {
            $("#addSaveBtn").off("click").on("click", function () {
                var bv = $('#roleManageForm').data('bootstrapValidator');
                bv.validate();
                if (bv.isValid()) {
                    $.ajax({
                        type: "post",
                        url: basePath + "rest/role/roleAdd",
                        data: $("#roleModal form").serialize(),
                        success: function (data) {
                            if (data.type == "success") {
                                $("#roleModal").modal("hide");
                                $("#roleTable").bootstrapTable("refresh");
                                toastr.success("角色添加成功");
                            } else {
                                toastr.error(data.message);
                            }
                        }
                    });
                }
            });
        }
    };

    // 修改角色
    var roleEditFun = {
        init: function () {
            roleEditFun.openEditModal();
            roleEditFun.formInit();
            roleEditFun.save();
        },
        openEditModal: function () {
            $("#editBtn").off("click").on("click", function () {
                var rows = $("#roleTable").bootstrapTable("getSelections");
                if (rows.length == 0) {
                    toastr.error('请选择行');
                } else if(rows.length > 1) {
                    toastr.error('单次只能选择一行进行修改');
                }else{
                    var roleId = rows[0].id;
                    $("#roleId").val(roleId);
                    $("#editRoleModal").modal("show");
                }
            });
        },
        formInit: function () {
            // 初始化表单
            $("#editRoleModal").on("show.bs.modal", function () {
                var roleId = $("#roleId").val();
                // 赋值
                $.ajax({
                    type: "post",
                    url: basePath + "rest/role/roleGetByPK",
                    data: {id: roleId},
                    success: function (data) {
                        if (data != null) {
                            $("#editRoleModal input[name='code']").val(data.code).attr("oldValue", data.code);
                            $("#editRoleModal input[name='name']").val(data.name).attr("oldValue", data.name);
                            $("#editRoleModal :input[name='description']").val(data.description);
                            var parentId = data.parentroleid;
                            $("#editParentSelect").html("<option value=\"\">请选择</option>");
                            $.get(basePath + "rest/role/parentRoleAll", function (parent) {
                                $.each(parent, function (index, role) {
                                    if(role.id != roleId){
                                        // 排除掉自身id
                                        if (role.id == parentId) {
                                            $("#editParentSelect").append("<option value=\"" + role.id + "\" selected>" + role.name + "</option>");
                                        } else {
                                            $("#editParentSelect").append("<option value=\"" + role.id + "\">" + role.name + "</option>");
                                        }
                                    }
                                });
                                $("#editParentSelect").selectpicker('refresh');
                                $("#editParentSelect").selectpicker('render');
                            });
                        }
                    }
                });
            });
        },
        save: function () {
            $("#editSaveBtn").off("click").on("click", function () {
                var bv = $('#editRoleForm').data('bootstrapValidator');
                var rows = $("#roleTable").bootstrapTable("getSelections");
                if (rows[0].parentroleid!=null){
                    var flag=false;
                    $.get(basePath + "rest/role/parentRoleAll", function (data) {
                        $.each(data, function (index, role) {
                            if(role.id==rows[0].parentroleid){
                                flag=true;
                            }
                        });
                        if(!flag){
                            toastr.error("由于该角色父角色级别大于您，您无权修改");
                            return;
                        }
                        bv.validate();
                        if (bv.isValid()) {
                            $.ajax({
                                type: "post",
                                url: basePath + "rest/role/roleUpdate",
                                data: $("#editRoleModal form").serialize(),
                                success: function (data) {
                                    if (data.type == "success") {
                                        $("#editRoleModal").modal("hide");
                                        $("#roleTable").bootstrapTable("refresh");
                                        toastr.success("角色修改成功");
                                    } else {
                                        toastr.error(data.message);
                                    }
                                }
                            });
                        }
                    });
                }else {
                    bv.validate();
                    if (bv.isValid()) {
                        $.ajax({
                            type: "post",
                            url: basePath + "rest/role/roleUpdate",
                            data: $("#editRoleModal form").serialize(),
                            success: function (data) {
                                if (data.type == "success") {
                                    $("#editRoleModal").modal("hide");
                                    $("#roleTable").bootstrapTable("refresh");
                                    toastr.success("角色修改成功");
                                } else {
                                    toastr.error(data.message);
                                }
                            }
                        });
                    }
                }
            });
        }
    };

    // 状态修改
    var statusChangeFun = {
        init: function () {
            statusChangeFun.batchOn();
            statusChangeFun.batchOff();
        },
        batchOn: function () {
            // 批量启用按钮事件绑定
            $("#batchOnBtn").off("click").on("click", function () {
                statusChangeFun.batch(1);
            });
        },
        batchOff: function () {
            // 批量停用按钮事件绑定
            $("#batchOffBtn").off("click").on("click", function () {
                statusChangeFun.batch(0);
            });
        },
        batch: function (status) {
            // 先获取要启用或停用的角色id
            var rows = $("#roleTable").bootstrapTable("getSelections");
            if (rows.length == 0) {
                toastr.error('请至少选择一条角色信息');
            } else {
                var idList = [];
                var statusStr = "";
                $.each(rows, function (index, row) {
                    idList.push(row.id);
                    statusStr += row.status;
                });
                if(statusStr.indexOf(status) > -1){
                    var str = status == 1 ? "启用" : "停用";
                    toastr.error('包含已' + str + "角色信息！");
                    return;
                }
                // 批量操作
                $.ajax({
                    type: "post",
                    url: basePath + "rest/role/roleStatusBatch",
                    data: {idList: idList, status: status},
                    traditional: true,
                    success: function (data) {
                        if (data.type == "success") {
                            toastr.success("角色状态批量修改成功");
                        } else {
                            toastr.error("角色状态批量修改失败");
                        }
                        $("#roleTable").bootstrapTable("refresh");
                    }
                });
            }
        }
    };

    // 角色删除
    var roleDeleteFun = {
        init: function () {
            roleDeleteFun.batch();
            roleDeleteFun.remindConfirm();
            roleDeleteFun.confimDelete();
            roleDeleteFun.delChildConfirm();
        },
        batch: function () {
            // 批量删除按钮事件绑定
            $("#batchDeleteBtn").off("click").on("click", function () {
                // 初始化要删除的id值
                $("#deleteId").val("");
                // 先获取选中的行
                var rows = $("#roleTable").bootstrapTable("getSelections");
                if (rows.length == 0) {
                    toastr.error('请选择行');
                } else {
                    var ids = [];
                    var isCanDelete = true;
                    $.each(rows, function (index, row) {
                        if(row.status == 1){
                            isCanDelete = false;
                        }
                        ids.push(row.id);
                    });
                    if(!isCanDelete){
                        toastr.error('要删除的角色已启用，不可以删除');
                        return false;
                    }
                    //判断角色是否包含子角色，若包含，提示、不进行删除
                    $.get(basePath + "rest/role/checkRoleHavChild?idList=" + ids, function (data) {
                        if(data.type == "fail"){
                            toastr.error('要删除的角色下包含的子角色正在使用中，不可删除');
                            return false;
                        }else if(data.type == "warning"){
                            // 确认是否与子角色一同删除
                            $("#deleteId").val(ids.join(","));
                            $("#delChildModal").modal("show");
                        }else{
                            // 判断要删除的角色是否在使用或者已授权
                            $.get(basePath + "rest/role/checkRoleIsUsing?idList=" + ids, function (data) {
                                $("#deleteId").val(ids.join(","));
                                if(data.type == "success"){
                                    // 弹出删除确认模态框
                                    $("#enshureModal").modal("show");
                                }else{
                                    // 角色删除需要二次确认
                                    $("#tipsModal").modal("show");
                                }
                            });
                        }
                    });

                }
            });
        },
        remindConfirm: function(){
            // 在提示模态框中点击确定时触发的事件绑定
            $("#tipsModal .csavebtn").off("click").on("click", function () {
                // 弹出删除确认模态框
                $("#tipsModal").modal("hide");
                $("#enshureModal").modal("show");
            });
        },
        delChildConfirm: function(){
            // 在提示模态框中点击确定时触发的事件绑定
            $("#delChildModal .csavebtn").off("click").on("click", function () {
                $("#delChildModal").modal("hide");
                var idList = $("#deleteId").val().split(",");
                // 判断要删除的角色是否在使用或者已授权
                $.get(basePath + "rest/role/checkRoleIsUsing?idList=" + idList, function (data) {
                    if(data.type == "success"){
                        // 弹出删除确认模态框
                        $("#enshureModal").modal("show");
                    }else{
                        // 角色删除需要二次确认
                        $("#tipsModal").modal("show");
                    }
                });
            });
        },
        confimDelete: function () {
            // 在删除模态框中点击确定时触发的删除事件绑定
            $("#enshureModal .csavebtn").off("click").on("click", function () {
                var idList = $("#deleteId").val().split(",");
                $.ajax({
                    type: "post",
                    url: basePath + "rest/role/roleDeleteBatch",
                    data: {idList: idList},
                    traditional: true,
                    success: function (data) {
                        // 相应后关闭model框
                        $("#enshureModal").modal("hide");
                        if (data.type == "success") {
                            toastr.success('删除成功');
                        } else {
                            toastr.error('删除失败');
                        }
                        // 刷新表格
                        $("#roleTable").bootstrapTable("refresh");
                    }
                });
            });
        }
    };

    // 基础功能
    var baseFun = {
        init: function () {
            baseFun.search();
            baseFun.roleRefresh();
            baseFun.reset();
        },
        // 点击搜索时表格重新加载
        search: function () {
            $("#searchBtn").off("click").on("click", function () {
                $("#roleTable").bootstrapTable('refreshOptions', {pageNumber:1});
                 $("#roleTable").bootstrapTable('refresh');
            });
            $("body").on("keyup", function (e) {
                var code = e.charCode || e.keyCode;
                if (code == 13) {
                    //此处编写用户敲回车后的代码
                    $("#roleTable").bootstrapTable('refreshOptions', {pageNumber:1});
                    $("#roleTable").bootstrapTable('refresh');
                }
            })
        },
        // 点击系统角色刷新时表格重新加载
        roleRefresh: function () {
            $("#refreshRoleBtn").off("click").on("click", function () {
                // 清空删选条件
                $("#statusSearch").val("");
                $("#statusSearch").selectpicker('refresh');
                $("#codeSearch").val("");
                $("#nameSearch").val("");
                $("#roleTable").bootstrapTable('destroy');
                // 重新构建table
                var oTable = new TableInit();
                oTable.Init();
            });
        },
        reset:function(){
            $("#reset").on("click", function () {
                bs.resetSearch($(".cquery"));
                $("#statusSearch").selectpicker("val","")
                $("#statusSearch").selectpicker("refresh")
                $("#roleTable").bootstrapTable('refreshOptions', {pageNumber:1});
                $("#roleTable").bootstrapTable('refresh');
            })
        }
    };

    //角色授权
    var authorFun = {
        init: function () {
            authorFun.openAuthorModal();
            authorFun.treeInit();
            authorFun.save();
        },
        openAuthorModal: function () {
            $("#authorBtn").off("click").on("click", function () {
                var rows = $("#roleTable").bootstrapTable("getSelections");
                if (rows.length == 0) {
                    toastr.error('请选择行');
                } else if(rows.length > 1) {
                    toastr.error('单次只能选择一个角色进行授权');
                }else{
                    // 获取要授权的角色id
                    var roleId = rows[0].id;
                    var roleName = rows[0].name;
                    var status = rows[0].status;
                    // 判断角色是否停用
                    if(status == 0){
                        toastr.error('角色已停用，不可授权');
                    }else{
                        $("#authRoleId").val(roleId);
                        $("#roleName").text(roleName);
                        $("#authorModel").modal("show");
                    }
                }
            });
        },
        treeInit: function(){
            $("#authorModel").on("show.bs.modal", function () {
                // 树初始化
                $("#authorTree").jstree("destroy");
                $("#authorTree").data('jstree', false).empty();
                $("#authorTree").jstree({
                    "core": {
                        "animation": false,
                        "multiple": true,
                        "check_callback": true,
                        'data': function (obj, callback) {
                            $.ajax({
                                type: "GET",
                                url: basePath + '/rest/permission/showResourceTree',
                                dataType: "json",
                                async: false,
                                success: function (result) {
                                    if (result != null) {
                                        var arr = [];
                                        arr.push(result);
                                        callback.call(this, authorFun.loopMenu(arr));
                                    }
                                }
                            });
                        }
                    },
                    "types": {
                        "default": {
                            "icon": "jstree-folder"
                        },
                        "html": {
                            "icon": "jstree-file"
                        }
                    },
                    "plugins": ["types", "search", "unique", "checkbox"],
                    "checkbox" : {
                        "keep_selected_style" : false
                    }
                }).on("loaded.jstree", function (e, data) {
                    // 初始化选择项
                    var instance = data.instance;
                    // 获取已选中的菜单项
                    $.ajax({
                        type: "post",
                        url: basePath + "rest/permission/permissionGet",
                        data: {roleId: $("#authRoleId").val()},
                        success: function (data) {
                            if (data != null && data.length > 0) {
                                $.each(data, function (i, resource) {
                                    if(resource != null){
                                        instance.select_node(resource.id);
                                    }
                                });
                            }
                        }
                    });
                });
            });
        },
        save: function(){
            $("#authorSaveBtn").off("click").on("click", function () {
                var roleId = $("#authRoleId").val();
                var resourceIdList = $("#authorTree").jstree("get_selected");
                // 保存资源id
                $.ajax({
                    type: "post",
                    url: basePath + "rest/permission/permissionSet",
                    data: {roleId: roleId, idList: resourceIdList},
                    traditional: true,
                    success: function (data) {
                        if (data != null) {
                            if (data.type == "success") {
                                toastr.success('授权成功');
                                $("#authorModel").modal("hide");
                            } else {
                                toastr.error('授权失败');
                            }
                        }
                    }
                });
            });
        },
        loopMenu: function (array) {
            if (array.length > 0) {
                for (var i = 0; i < array.length; i++) {
                    var children = array[i]["children"];
                    if (children.length <= 0) {
                        array[i].type = "html"
                    } else {
                        array[i].state = {"opened": "false"}
                    }
                    if (children) {
                        authorFun.loopMenu(children);
                    }
                }
                return array;
            }
        }
    };

    //添加相关
    var prosess = {
        init: function () {
            this.initKeyValidator();
            this.initOpen();
        },
        initKeyValidator: function () {
            var option = {
                live: "enabled",
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    code: {
                        validators: {
                            notEmpty: {
                                message: '角色标识不能为空'
                            },
                            stringLength: {
                                max: 20,
                                message: '最大长度为20个字符'
                            },
                            callback: {
                                message: '该值已存在',
                                callback: function (value, validator, $field) {
                                    if (value == $field.attr("oldvalue")) {
                                        return true;
                                    }
                                    var isExist = false;
                                    $.ajax({
                                        type: "post",
                                        async: false,
                                        url: basePath + "rest/role/codeUniqueCheck",
                                        data: {code: value},
                                        success: function (data) {
                                            if (data.type == "success") {
                                                isExist = true;
                                            }
                                        }
                                    });
                                    return isExist;
                                }
                            }
                        }
                    },
                    name: {
                        validators: {
                            notEmpty: {
                                message: '角色名称不能为空'
                            },
                            stringLength: {
                                max: 20,
                                message: '最大长度为20个字符'
                            },
                            callback: {
                                message: '该值已存在',
                                callback: function (value, validator, $field) {
                                    if (value == $field.attr("oldvalue")) {
                                        return true;
                                    }
                                    var isExist = false;
                                    $.ajax({
                                        type: "post",
                                        async: false,
                                        url: basePath + "rest/role/nameUniqueCheck",
                                        data: {name: value},
                                        success: function (data) {
                                            if (data.type == "success") {
                                                isExist = true;
                                            }
                                        }
                                    });
                                    return isExist;
                                }
                            }
                        }
                    }
                }
            };
            $('#roleManageForm').bootstrapValidator(option);
            $('#editRoleForm').bootstrapValidator(option);
        },
        initOpen: function () {
            $("#roleModal").on("hide.bs.modal", function () {
                $('#roleManageForm').data('bootstrapValidator').resetForm(true);
            });
            $("#editRoleModal").on("hide.bs.modal", function () {
                $('#editRoleForm').data('bootstrapValidator').resetForm(true);
            });
        }
    };

    var resize = {
        init: function () {
            resize.me();
            $(window).resize(function () {
                resize.me();
            })
        },
        me: function () {
            var winW = $(window).width();
            var winH = $(window).height();
            $(".ibox").width(winW - 20);
            $(".ibox").height(winH - 20);
            bs.autoTableHeight($('#roleTable'),winH -$(".cquery").height()-22-$(".obtns").height())
        }
    };
    $(function () {
        // 表格初始化
        var oTable = new TableInit();
        oTable.Init();
        baseFun.init();
        statusChangeFun.init();
        roleDeleteFun.init();
        roleAddFun.init();
        roleEditFun.init();
        authorFun.init();
        prosess.init();
        resize.init();
    });
</script>
</body>
</html>